<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import * as echarts from 'echarts'

interface SensorData {
  id: string
  name: string
  value: number
  timestamp: string
}

const props = defineProps<{
  sensorData: SensorData[]
  timestamp: string
}>()

const chartDom = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 处理传感器数据
const processedData = computed(() => {
  const defaultData = [
    { value: 0, name: '土壤温度', itemStyle: { color: '#4fd2dd' } },
    { value: 0, name: '土壤PH值', itemStyle: { color: '#ffc93c' } },
    { value: 0, name: '空气温度', itemStyle: { color: '#ff6e76' } },
    { value: 0, name: '氮含量', itemStyle: { color: '#73c0de' } },
    { value: 0, name: '磷含量', itemStyle: { color: '#3ba272' } },
    { value: 0, name: '钾含量', itemStyle: { color: '#fc8452' } }
  ]

  if (!props.sensorData?.length) return defaultData

  // 获取处理后的数据
  const processedValues = defaultData.map(item => {
    const sensor = props.sensorData.find(s => {
      if (item.name === '土壤温度') return s.name.includes('土壤') && s.name.includes('温度')
      if (item.name === '土壤PH值') return s.name.includes('PH') || s.name.includes('ph')
      if (item.name === '空气温度') return s.name.includes('空气') && s.name.includes('温度')
      if (item.name === '氮含量') return s.name.includes('氮')
      if (item.name === '磷含量') return s.name.includes('磷')
      if (item.name === '钾含量') return s.name.includes('钾')
      return false
    })

    return {
      ...item,
      realValue: sensor ? sensor.value : 0, // 保存真实值
      value: sensor ? sensor.value : 0 // 这个值后面会被调整
    }
  })

  // 计算总值（不包括为0的值）
  const totalValue = processedValues.reduce((sum, item) => sum + (item.value > 0 ? item.value : 0), 0)
  
  // 如果所有值都为0，给每个项目相等的比例
  if (totalValue === 0) {
    return processedValues.map(item => ({
      ...item,
      value: 1, // 相等的比例
      realValue: 0 // 保持真实值为0
    }))
  }

  // 调整值，让0值项目也有一定比例
  return processedValues.map(item => ({
    ...item,
    value: item.value > 0 ? item.value : totalValue * 0.03, // 0值项目占总值的3%
    realValue: item.realValue // 保持真实值不变
  }))
})

// 更新图表
const updateChart = () => {
  if (!chart) return

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const { name, data } = params
        const value = data.realValue // 使用真实值
        if (name.includes('温度')) return `${name}: ${value}℃`
        if (name.includes('PH')) return `${name}: ${value}pH`
        return `${name}: ${value}mg/kg`
      }
    },
    legend: {
      orient: 'vertical',
      left: '5%',
      top: 'center',
      textStyle: {
        color: '#4fd2dd'
      }
    },
    series: [
      {
        name: '土壤数据',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#001529',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: (params: any) => {
            const value = params.data.realValue // 使用真实值
            if (params.name.includes('温度')) return `${value}℃`
            if (params.name.includes('PH')) return `${value}pH`
            return `${value}mg/kg`
          },
          color: '#fff',
          fontSize: 14
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: processedData.value
      }
    ]
  }
  
  chart.setOption(option)
}

const initChart = () => {
  if (chartDom.value) {
    chart = echarts.init(chartDom.value)
    updateChart()
  }
}

// 监听数据变化
watch(() => props.sensorData, () => {
  console.log('土壤数据更新:', props.sensorData)
  updateChart()
}, { deep: true })

const resizeHandler = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  chart?.dispose()
})
</script>

<template>
  <div ref="chartDom" class="pie-chart"></div>
</template>

<style scoped>
.pie-chart {
  width: 100%;
  height: 100%;
}
</style>